/**
 * @(#)VelocityService.java 2011-9-21
 * 
 * Copyright 2000-2011 by ChinanetCenter Corporation.
 *
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * ChinanetCenter Corporation ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with ChinanetCenter.
 * 
 */

package com.szf.base.service;

import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.szf.base.exception.GenericException;

/**
 * 提供解析velocity vm模板文件或模板内容的服务类
 * 
 * @author 刘圳
 * @version 1.0 2011-9-21
 * @since 2.0
 */
@SuppressWarnings("rawtypes")
public class VelocityService {

	private VelocityEngine velocityEngine;
	private String filePrefix;

	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}

	public void setFilePrefix(String filePrefix) {
		this.filePrefix = filePrefix;
	}

	public void mergeTemplate(String templateFile, Map model, Writer writer) {
		VelocityEngineUtils.mergeTemplate(velocityEngine, filePrefix + templateFile, model, writer);
	}

	public String mergeTemplateIntoString(String templateFile, Map model) {
		return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, filePrefix + templateFile, model);
	}

	public void mergeContent(String inContent, Map model, Writer writer) {
		VelocityContext velocityContext = new VelocityContext(model);
		try {
			velocityEngine.evaluate(velocityContext, writer, "VelocityService", inContent);
		} catch (Exception e) {
			throw new GenericException(e.getMessage(), e);
		}
	}

	public String mergeContentIntoString(String inContent, Map model) {
		StringWriter result = new StringWriter();
		mergeContent(inContent, model, result);
		return result.toString();
	}

}
